<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">

      <!-- 活动下拉框 -->
      <el-select v-model="groupQuery.activityId" placeholder="活动名称" @change="findGroup" filterable>
        <el-option v-for="activity in activityList" :key="activity.activityId" :label="activity.activityName"
                   :value="activity.activityId"/>
      </el-select>

      <!-- 活动下的分组 -->
      <el-select v-model="groupQuery.groupId" placeholder="分组名称" @change="getList(0)" filterable>
        <el-option v-for="group in groupList" :key="group.groupId" :label="group.groupName" :value="group.groupId"/>
      </el-select>

      <el-button type="default" @click="resetData">清空</el-button>
      <el-button type="primary" :disabled="increaseGroup" icon="el-icon-document-add" @click="addGroupInfo">新增分组
      </el-button>
    </el-form>

    <!-- 表格部分 -->
    <el-table :data="list" border fit highlight-current-row>

      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="activityName" label="活动名称"/>

      <el-table-column prop="groupName" label="组名"/>

      <el-table-column prop="description" label="组描述" show-overflow-tooltip/>

      <el-table-column prop="volunteerName" label="成员"/>

      <el-table-column prop="roleName" label="角色"/>

      <el-table-column label="操作" width="450" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit"
                     @click="openAddMemberListIntoGroup(scope.row.groupId)">批量增加成员
          </el-button>
          <el-button type="primary" size="mini" icon="el-icon-edit"
                     @click="openAddMemberInfoGroup(scope.row.activityId,scope.row.activityName,scope.row.groupId,scope.row.groupName)">
            增加成员
          </el-button>
          <el-button type="primary" size="mini" icon="el-icon-edit"
                     @click="updateGroupInfo(scope.row.activityId,scope.row.activityName,scope.row.groupId,scope.row.groupName,scope.row.description)">
            修改
          </el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.volunteerId)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹框部分 -->
    <!-- 增加或更新分组信息的弹框 -->
    <el-dialog :visible.sync="updateOrIncreaseGroupInfo" width="35%" title="分组信息">
      <el-form :model="groupInfo" label-width="150px">
        <el-form-item label="活动名称">
          <p>{{ this.groupInfo.activityName }}</p>
        </el-form-item>
        <el-form-item label="分组名称">
          <el-input v-model="groupInfo.groupName" clearable/>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input type="textarea" :rows="3" v-model="groupInfo.description" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateOrIncreaseGroupInfo = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateGroup">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 向分组添加组员的弹框(单个添加) -->
    <el-dialog :visible.sync="addMemberIntoGroup" width="45%" title="添加成员">
      <el-form :model="volunteerGroupInfo" label-width="150px">

        <el-form-item label="活动名称" style="width: 70%">
          <el-input v-model="volunteerGroupInfo.activityName" :disabled="true"/>
        </el-form-item>

        <el-form-item label="分组名称" style="width: 50%">
          <el-input v-model="volunteerGroupInfo.groupName" :disabled="true"/>
        </el-form-item>

        <!-- <el-form-item label="统一认证码">
          <p>{{ this.volunteerGroupInfo.stuId }}</p>
        </el-form-item>

        <el-form-item label="组员姓名">
          <el-select v-model="volunteerGroupInfo.volunteerId" placeholder="姓名" @change="findMemberId" filterable>
            <el-option v-for="member in idleList" :key="member.id" :label="member.username" :value="member.id"/>
          </el-select>
        </el-form-item> -->

        <el-form-item label="组员姓名">
          <el-select v-model="volunteerGroupInfo.volunteerId" placeholder="姓名" @change="findMemberId" filterable>
            <el-option v-for="member in idleList" :key="member.id" :label="member.authCode" :value="member.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="角色">
          <el-radio-group v-model="volunteerGroupInfo.roleId">
            <el-radio v-for="role in roleList" :key="role.roleId" :value="role.roleName" :label="role.roleId">
              {{ role.roleName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色任务描述">
          <el-input v-model="volunteerGroupInfo.roleDescription" clearable/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addMemberIntoGroup = false">取 消</el-button>
        <el-button type="primary" @click="addMemberIntoGroupFunc">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量添加组员，角色只能为志愿者或普通组员，组长和副组长用单个添加 -->
    <el-dialog title="批量添加组员" :visible.sync="addMemberListIntoGroup" width="45%">
      <el-select v-model="roleIdBatch" placeholder="角色名" filterable>
        <el-option v-for="role in roleListTemp" :key="role.roleId" :value="role.roleId" :label="role.roleName"/>
      </el-select>

      <el-table ref="volunteerGroupInfoListTable" tooltip-effect="dark" :data="idleList"
                @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="stuId" label="统一认证码" width="150"></el-table-column>
        <el-table-column property="username" label="姓名" width="155"></el-table-column>
        <el-table-column property="sex" label="性别" width="80">
          <template slot-scope="scope">
            {{ scope.row.sex === true ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column property="institution" label="所属学院" width="200"></el-table-column>
      </el-table>
      <br>
      <div>
        <el-button @click="addMemberListIntoGroup = false">取 消</el-button>
        <el-button @click="addMemberListIntoGroupFunc()" type="primary">添 加</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination :current-page="page" :page-size="limit" :total="total" background layout="prev, pager, next"
                   style="padding: 30px 0; text-align: center;" @current-change="getList"/>
  </div>

</template>
<script>
import group from '@/api/management/group'

export default {
  data() {
    return {
      list: [], //查询之后接口返回的集合
      page: 1,
      limit: 10,
      total: 0,
      roleIdBatch: '', //批量赋予角色信息，只能赋予普通组员或者志愿者，4为普通组员，5为志愿者
      updateOrIncreaseGroupInfo: false, //新增分组的弹框是否显示，false为不可见
      addMemberListIntoGroup: false, //批量添加组员的弹框是否可见
      increaseGroup: true, //如果活动名称的搜索框中有值才允许添加分组信息,true为不可点击
      addMemberIntoGroup: false, //向分组中增加成员弹框（单个添加）是否显示
      groupId: '', //用于批量增加组员时保存所在组的id
      groupInfo: {
        activityId: '',
        activityName: '',
        groupId: '',
        groupName: '',
        description: ''
      }, //保存新增或修改后的分组信息
      groupQuery: {
        activityId: '',
        activityName: '',
        groupId: '',
        groupName: ''
      }, //保存搜索框中的查询条件
      volunteerGroupInfo: {
        stuId: '',
        roleId: '',
        groupId: '',
        activityId: '',
        volunteerId: '',
        roleName: '',
        groupName: '',
        activityName: '',
        volunteerName: '',
        roleDescription: ''
      }, //保存新增组员的信息
      activityList: [], //活动列表
      groupList: [], //活动下的分组列表
      roleList: [], //表中所有的角色
      idleList: [],
      idleListTemp: [],
      roleListTemp: [{
        roleId: '4',
        roleName: '组员'
      }, {
        roleId: '5',
        roleName: '志愿者'
      }],
      volunteerGroupInfoList: [], //保存批量新增组员的信息
    }
  },
  created() {
    //获取获取所有分组下的人员信息
    this.getList()
    //获取每个活动，并带有活动下的分组信息，用于二级联动
    this.getActivityGroupInfo()
  },
  methods: {
    //查询每个活动下的分组信息,value会代表活动id
    findGroup(value) {
      for (var i = 0; i < this.activityList.length; i++) {
        let activity = this.activityList[i]
        if (value === activity.activityId) {
          this.groupList = activity.groups
          this.groupQuery.groupId = ''
        }
      }
      //将增加分组的按钮置为可点击状态
      this.increaseGroup = false
      this.getList()
    },
    //查询每个活动，并封装活动下的分组信息
    getActivityGroupInfo() {
      group.getActivityGroupInfo().then(response => {
        this.activityList = response.data.groupQuery
      })
    },
    getList(page = 1) {
      this.page = page
      group.groupManageByPage(this.page, this.limit, this.groupQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
        })
    },
    resetData() {
      //设置新增分组按钮不可用
      this.increaseGroup = true
      //清空查询条件
      this.groupQuery = {}
      this.groupList = {}
      this.getList()
    },
    //删除组内的成员
    removeDataById(volunteerId) {
      if (volunteerId === null) {
        this.$confirm('请往分组中添加一个成员，再执行此操作', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(response => {
        })
      } else {
        this.$confirm('此操作将删除改成员，是否确定', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(response => {
          group.deleteVolunteerFromGroup(volunteerId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成员成功!'
            });
            //刷新列表
            this.getList()
          })
        }).catch(response => {
        })
      }
    },
    //更新分组信息
    updateGroupInfo(activityId, activityName, groupId, groupName, description) {
      this.updateOrIncreaseGroupInfo = true
      this.groupInfo.activityId = activityId
      this.groupInfo.activityName = activityName
      this.groupInfo.groupId = groupId
      this.groupInfo.groupName = groupName
      this.groupInfo.description = description

    },
    //增加分组信息
    addGroupInfo() {
      this.updateOrIncreaseGroupInfo = true
      let obj = {}
      //获取下拉框中的value和label值
      obj = this.activityList.find(activity => activity.activityId === this.groupQuery.activityId)
      this.groupInfo.activityId = obj.activityId
      this.groupInfo.activityName = obj.activityName
      this.groupInfo.groupId = ''
      this.groupInfo.groupName = ''
      this.groupInfo.description = ''
    },
    //判断是更新还是新增
    saveOrUpdateGroup() {
      if (this.groupInfo.groupId === '') {
        this.saveAddGroupInfo()
      } else {
        this.saveUpdateGroupInfo()
      }
    },
    //保存更新的分组信息
    saveUpdateGroupInfo() {
      group.updateGroup(this.groupInfo).then(response => {
        //关闭弹窗
        this.updateOrIncreaseGroupInfo = false
        //给出提示信息
        //提示添加成功
        this.$message({
          type: 'success',
          message: '更新分组信息成功!'
        });
        //刷新列表
        this.getList()
      })
    },
    //保存新增的分组信息
    saveAddGroupInfo() {
      group.addGroup(this.groupInfo).then(response => {
        this.updateOrIncreaseGroupInfo = false
        this.$message({
          type: 'success',
          message: '增加分组信息成功!'
        });
        //刷新列表
        this.getList()
      })
    },
    //根据用户id查询学号
    findMemberId(id) {
      //查询选中用户的统一认证码,查到认证码后显示到页面
      group.getVolunteerById(id).then(response => {
        this.volunteerGroupInfo.stuId = response.data.volunteer.stuId
      })
    },
    //打开向分组中增加组员的弹框
    openAddMemberInfoGroup(activityId, activityName, groupId, groupName) {
      if (groupId === null) {
        this.$confirm('请至少新建一个分组，再添加组员', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(response => {
        })
      } else {
        //清空缓存
        this.volunteerGroupInfo.stuId = ''
        this.volunteerGroupInfo.roleId = ''
        this.volunteerGroupInfo.volunteerId = ''
        this.volunteerGroupInfo.volunteerName = ''
        this.volunteerGroupInfo.roleDescription = ''
        //回显信息
        this.addMemberIntoGroup = true
        this.volunteerGroupInfo.activityId = activityId
        this.volunteerGroupInfo.activityName = activityName
        this.volunteerGroupInfo.groupId = groupId
        this.volunteerGroupInfo.groupName = groupName
        //查询没有被分配任务的人员
        group.getMemberNotInGroup().then(response => {
          this.idleList = response.data.idleList
        })
        //查询所有的角色信息
        group.getRoleList().then(response => {
          this.roleList = response.data.roleList
        })
      }
    },
    //保存新增的组员信息
    addMemberIntoGroupFunc() {
      this.addMemberIntoGroup = false
      group.addMemberIntoGroup(this.volunteerGroupInfo).then(response => {
        this.$message({
          type: 'success',
          message: '增加组员成功!'
        });
        //刷新列表
        this.getList()
      })
    },
    //打开向批量增加组员的弹框
    openAddMemberListIntoGroup(groupId) {
      //1. 先初始化数据
      //查询没有分配被小组的人员
      group.getMemberNotInGroup().then(response => {
        this.idleList = response.data.idleList
      })
      //查询所有的角色信息
      group.getRoleList().then(response => {
        this.roleList = response.data.roleList
      })
      // 2. 打开弹框
      this.addMemberListIntoGroup = true
      this.groupId = groupId
    },
    handleSelectionChange(val) {
      //清空缓存
      this.volunteerGroupInfoList = []
      //获取选中的人员，CheckBox每次改变都会自动调用此方法
      this.idleListTemp = this.$refs.volunteerGroupInfoListTable.selection
      // 为集合中的volunteerId、groupId、roleId赋值
      let obj = {}
      //获取下拉框中的value和label值
      obj = this.roleListTemp.find(role => role.roleId === this.roleIdBatch)

      //初始化volunteerGroupInfoList的长度，否则会报错
      for (var i = 0; i < this.idleListTemp.length; i++) {
        //每次循环都需要重新定义，否则会因为浅拷贝造成集合中只存最后存入的值
        //let是块级作用域，函数内部使用let定义后，对函数外部无影响。
        let volunteerGroupInfoListTemp = {
          volunteerId: this.idleListTemp[i].id,
          groupId: this.groupId,
          roleId: obj.roleId,
          roleName: obj.roleName
        }
        this.volunteerGroupInfoList.push(volunteerGroupInfoListTemp)
      }
    },
    //批量增加组员
    //TODO应该对显示的未分配人员进行分页展示
    addMemberListIntoGroupFunc() {
      group.addMemberListIntoGroup(this.volunteerGroupInfoList).then(response => {
        this.$message({
          type: 'success',
          message: '批量增加组员成功!'
        });
        //刷新列表
        this.getList()
      })
      this.addMemberListIntoGroup = false
    }
  }

}
</script>
<style scoped>
.el-form-item p {
  display: inline-block;
  margin: 0;
  padding: 0
}

.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /*height:600px;*/
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>
